<template>
	<view @click="chatType =''">
		<dsl-navbar :title="ta_name" bgTopImg="white" isBack right1='/static/chat/imgjiahaoyou-1.png'
			right2='/static/chat/shenglue.png' @right1Men='right1Men' @right2Men='right2Men'></dsl-navbar>
		<view class="chat_top align-center rowsc ">
			<text>以为你设置防骚扰，对方须支付2钻石/条消息</text>
			<image src="/static/chat/imgchahao-1.png" mode="" style="width: 30rpx;height: 30rpx; margin-left: 50rpx;">
			</image>
		</view>
		<view class="padding text-center text-sm text-gray" @click="messagePaging()">查看更多聊天信息</view>
		<view v-if="message && message.length !=0">
			<view v-for="(item,index) in message" :key="index">
				<view class="text-center text-sm margin-top-sm" style="color: #B7BED8;" v-if="index%2 !=0">
					{{item.createTime}}
				</view>
				<!-- 自己的 -->
				<view class="flex margin-right justify-end" v-if="item.uid == user_id">
					<view class="flex justify-end" style="width: 450rpx;">
						<view class="chat_right " v-if="item.type == 'text'">
							{{item.content}}
						</view>
						<view v-if="item.type =='image'" class="chat_right" @click="imagePreview(0,[item.content])">
							<image :src="item.content" mode="widthFix" class="chat_image"></image>
						</view>
						<view v-if="item.type =='icon'" class="chat_right" @click="imagePreview(0,[item.content])">
							<image :src="item.content" class="chat_icon"></image>
						</view>
						<view v-if="item.type =='audio'" class="chat_right align-center">
							<image :src="true?'/static/chat/audio3.png':'/static/chat/play.gif'" mode=""
								class="chat_audio"></image>
							<text class="text-black">3</text>
						</view>
					</view>
					<image :src="user_avatar?user_avatar:'/static/user/userImg.png'" mode="" class="user_image"
						@click="$tools.push('/pages/user/modules/userInfo?id='+user_id)"></image>
				</view>
				<!-- 对面的 -->
				<view class="flex margin-left" v-else>
					<image :src="ta_avatar?ta_avatar:'/static/user/userImg.png'" mode="" class="user_image"
						@click="$tools.push('/pages/user/modules/userInfo?id='+ta_id)">
					</image>
					<view class="chat_left" v-if="item.type == 'text'">
						{{item.content}}
					</view>
					<view v-if="item.type =='image'" class="chat_left" @click="imagePreview(0,[item.content])">
						<image :src="item.content" mode="widthFix" class="chat_image"></image>
					</view>
					<view v-if="item.type =='icon'" class="chat_left" @click="imagePreview(0,[item.content])">
						<image :src="item.content" class="chat_icon"></image>
					</view>
					<view v-if="item.type =='audio'" class="chat_left">
						语音
					</view>
				</view>
			</view>
		</view>
		<view style="height: 260rpx;" v-if="isChatBottom"></view>
		<view style="height: 100rpx;" v-if="!isChatBottom"></view>
		<view class="fixed bg-white" style="bottom: 0;">
			<view class="message align-center" v-if="false">
				<view class=" flex">
					<view style="width: 100rpx;">
						<image src="/static/chat/imgxiaoxi-5.png" mode="" style="width: 30rpx;height: 30rpx;"
							class="margin-left-xs "></image>
					</view>
					<view class="">
						平台倡导绿色聊天，严禁色情暴力，低俗不良的聊天行为将被禁止；
						自动屏蔽敏感信息和数字（微信号、QQ号等...）
					</view>
				</view>
			</view>
			<view class="chat_input align-center padding-lr justify-between">
				<input type="text" value="" placeholder="请输入内容..." placeholder-style="color:#B7BED8"
					style="width: 500rpx;" @confirm.stop="msgConfirm" v-model="inputValue" />
				<view hover-class="bg-gray round">
					<image src="/static/chat/kefu_jianghua-4.png" mode="" style="width: 70rpx;height: 70rpx;"
						@touchstart="audioStart" @touchend="audioEnd"></image>
				</view>
			</view>
			<view class="padding bg-white align-center justify-between margin-top">
				<view v-for="(item,index) in list" :key="index" @click.stop="msgSubmit(index)">
					<image :src="item" mode="" class="message_icon"></image>
				</view>
			</view>
			<!--    emoji部分-->
			<view class="bottom-emoji animation-slide-bottom" v-if="chatType=='emoji'">
				<view class="emojis">
					<view v-for="(emojiItem, index3) in emojiName" class="emoji" :key="emojiItem"
						@click.stop="msgSubmit(5,emojiUrl + emojiMap[emojiItem])">
						<image :src="emojiUrl + emojiMap[emojiItem]" style="width:100%;height:100%" />
					</view>
				</view>
			</view>
		</view>
		<view class="voice_an" v-if="isAudioPlay">
			<view class="voice_an_icon">
				<view id="one" class="wave"></view>
				<view id="two" class="wave"></view>
				<view id="three" class="wave"></view>
				<view id="four" class="wave"></view>
				<view id="five" class="wave"></view>
				<view id="six" class="wave"></view>
				<view id="seven" class="wave"></view>
			</view>
			<view class="text">录音中...</view>
		</view>
	</view>
</template>

<script>
	// #ifdef H5
	import Recorder from 'js-audio-recorder';
	const lamejs = require('lamejs')
	const recorder = new Recorder({
		sampleBits: 16, // 采样位数，支持 8 或 16，默认是16
		sampleRate: 48000, // 采样率，支持 11025、16000、22050、24000、44100、48000，根据浏览器默认值，我的chrome是48000
		numChannels: 1, // 声道，支持 1 或 2， 默认是1
		// compiling: false,(0.x版本中生效,1.x增加中)  // 是否边录边转换，默认是false
	})
	// #endif

	// #ifdef APP-PLUS
	const audioContext = uni.createInnerAudioContext(); //播放音频
	const recorderManager = uni.getRecorderManager(); // 录制音频
	audioContext.autoplay = false;
	// #endif

	import {
		mapState,
		mapActions
	} from 'vuex'
	export default {
		data() {
			return {
				inputValue: '', //消息内容
				chatType: '', //消息状态
				ta_avatar: '', //头像
				ta_name: '', //名称
				pageNum: 1, //第一页
				isChatBottom: false,
				isAudioPlay: false, //是否显示 录音中
				ta_id: '', //对面id


				audioContextSrc: '', //本地语音文件
				audioContextUrl: '', //接口语音文件
				isRecordStart: '', //是否运行倒计时
				setInterDate: 0, //倒计时数字
			}
		},
		components: {},

		watch: {
			//监听消息变化
			message(e) {
				// console.log('[消息]', e);
				this.pageScrollToMax()
				setTimeout(r => {
					this.isChatBottom = true
				}, 1000)
			},
			//监听音频变化
			audioContextSrc(event) {
				audioContext.src = event
				console.log('[触发播放音频]', audioContext.src);
				this.isSetIntervalF() //销毁倒计时
				this.sendAudio(url, Number(this.setInterDate))
				let url = audioContext.src
			},

		},
		//卸载
		onUnload() {
			// #ifdef APP-PLUS
			audioContext.destroy() //销毁当前实例
			// #endif
		},
		//生命周期函数
		onReady() {},
		onLoad(option) {
			this.ta_avatar = getApp().globalData.taAvatar
			this.ta_name = option.userName
			if(uni.getStorageSync('ta_id')){
				this.ta_id = uni.getStorageSync('ta_id')
			}
			this.setTaid(uni.getStorageSync('ta_id'))
			this.audioContext() //音频初始化
			this.chatMessage() //消息列表
			this.readAllMessageApi({
				userId: this.user_id,
				taId: uni.getStorageSync('ta_id')
			}) //消息已读


		},
		onShow() {},
		computed: {
			/**
			 * @description vuex功能
			 *  emojiName 表情包
			 *  emojiMap 表情包
			 *  emojiUrl 表情包拼接
			 *  list 底部的5块功能
			 *  webSocket ws链接
			 *  message 聊天消息1v1
			 *  user_id 我的id
			 *  ta_id 对面id
			 *  user_avatar 自己头像
			 */

			...mapState('chat', [
				'emojiName',
				'emojiMap',
				'emojiUrl',
				'list',
				'webSocket',
				'message',
				'user_id',
				'ta_id',
				'user_avatar',
			])
		},
		methods: {
			/**
			 * @description vuex功能
			 *  cooseText 发文字 
			 *  cooseGift 礼物 
			 *  chooseVideo 视频通话
			 *  chooseCamera 发拍照
			 *  chooseImage 发图片
			 *  cooseEmoji 发表情包
			 *  openSocket 初始化ws
			 *  sendMessag 发送消息
			 *  pageScrollToMax 弹到最底下
			 *  chatMessageApi 消息内容
			 *  sendAudio 发送语音
			 */
			...mapActions('chat',
				[
					'cooseText',
					'cooseGift',
					'chooseVideo',
					'chooseCamera',
					'chooseImage',
					'openSocket',
					'cooseEmoji',
					'sendMessag',
					'pageScrollToMax',
					'showActionSheet',
					'chatMessageApi',
					'sendAudio',
					'readAllMessageApi',
					'addFriend',
					'setTaid'
				]),
			//音频初始化
			audioContext() {
				// #ifdef APP-PLUS ||MP-WEIXIN
				let self = this
				recorderManager.onStop(res => { // 结束录音 自动触发
					self.audioContextSrc = res.tempFilePath
					self.$tools.showToast(res.tempFilePath)

					// console.log('[录音]', res);
				})
				audioContext.src = this.audioContextSrc
				audioContext.onEnded((e) => { //音频自然结束
					// console.log('[结束]');
				})
				// #endif
			},
			//添加好友
			right1Men() {
				this.addFriend({
					userId: this.user_id,
					friendId: uni.getStorageSync('ta_id')
				})
			},
			//录音开始
			audioStart() {
				// #ifdef H5
				recorder.start();
				// #endif
				this.isAudioPlay = true
				// #ifdef APP-PLUS || MP-WEIXIN
				recorderManager.start()
				this.isSetInterval()
				// #endif
			},
			//倒计时
			isSetInterval() {
				this.isRecordStart = setInterval(r => {
					this.setInterDate += 0.1
				}, 100)
			},
			//销毁倒计时
			isSetIntervalF() {
				this.setInterDate = 0
				clearInterval(this.isRecordStart) //销毁倒计时
			},
			//录音结束
			audioEnd() {
				// #ifdef H5
				recorder.stop();
				let num = Number(recorder.duration)
				console.log('[录音时长]', num);
				if (num <= 1) {
					this.$tools.showToast('录音时长少于1秒！')
					this.isAudioPlay = false
					return
				}
				let urlBold = this.convertToMp3(recorder.getWAV())
				let urlBold2ces = recorder.getWAV()
				let audioUrl = URL.createObjectURL(urlBold)
				if (audioUrl) {
					uni.hideLoading()
					setTimeout(r => {
						uni.showToast({
							title: '语音生成成功',
							icon: 'none'

						})
						this.isAudioPlay = false
					}, 100)
				}

				this.sendAudio(audioUrl, num)
				// #endif

				// #ifdef APP-PLUS
				recorderManager.stop() //结束 录音
				audioContext.pause(); //暂停 播放
				this.isAudioPlay = false //隐藏录音中弹窗
				// #endif


				audioContext.play() //开始 播放
			},
			//音频转MP3
			convertToMp3(wavDataView) {
				// 获取wav头信息
				const wav = lamejs.WavHeader.readHeader(wavDataView); // 此处其实可以不用去读wav头信息，毕竟有对应的config配置
				const {
					channels,
					sampleRate
				} = wav;
				const mp3enc = new lamejs.Mp3Encoder(channels, sampleRate, 128);
				// 获取左右通道数据
				const result = recorder.getChannelData()
				const buffer = [];

				const leftData = result.left && new Int16Array(result.left.buffer, 0, result.left.byteLength / 2);
				const rightData = result.right && new Int16Array(result.right.buffer, 0, result.right.byteLength / 2);
				const remaining = leftData.length + (rightData ? rightData.length : 0);

				const maxSamples = 1152;
				for (let i = 0; i < remaining; i += maxSamples) {
					const left = leftData.subarray(i, i + maxSamples);
					let right = null;
					let mp3buf = null;

					if (channels === 2) {
						right = rightData.subarray(i, i + maxSamples);
						mp3buf = mp3enc.encodeBuffer(left, right);
					} else {
						mp3buf = mp3enc.encodeBuffer(left);
					}

					if (mp3buf.length > 0) {
						buffer.push(mp3buf);
					}
				}

				const enc = mp3enc.flush();

				if (enc.length > 0) {
					buffer.push(enc);
				}

				return new Blob(buffer, {
					type: 'audio/mp3'
				});
			},
			//图片预览
			imagePreview(index, array) {
				uni.previewImage({
					current: index,
					urls: array,
					longPressActions: {
						itemList: ['发送给朋友', '保存图片', '收藏'],
					}
				})
			},
			//消息列表
			chatMessage() {
				this.isChatBottom = false
				this.chatMessageApi({
					"userId": this.user_id,
					"taId": uni.getStorageSync('ta_id'),
					"pageNum": this.pageNum,
					"pageSize": 10
				})
			},
			//从下往上分页
			messagePaging() {
				this.pageNum++
				this.chatMessage()
			},
			//顶部更多功能
			right2Men() {
				this.showActionSheet()
			},
			//发送消息
			msgConfirm(event) {
				let type = ''
				if (event.detail.value) { //消息类型
					type = 'text'
				} else {
					type = event.type
				}
				let data = {
					type: 'text', //消息类型 （图片，视频，语音,文字）
					content: this.inputValue, //消息内容
					uid: this.user_id, //1自己 0对面
				}

				this.sendMessag(data)
				this.inputValue = ''

			},
			//消息组建
			msgSubmit(i, icon) {
				this.isChatBottom = true
				if (i == 0) { //视频
					// this.chooseVideo()
					uni.navigateTo({
						url: 'videoPlay'
					})
				} else if (i == 1) { //图片
					this.chooseImage()
				} else if (i == 2) { //礼物
					this.cooseGift()
				} else if (i == 3) { //拍照
					this.chooseCamera()
				} else if (i == 4) { //打开表情组建
					this.chatType = 'emoji'
				} else if (i == 5) {
					this.cooseEmoji(icon)
				}
			}
		},
	}
</script>

<style lang="scss">
	page {
		background-color: #F7F6FA;
	}

	.chat_top {
		width: 690rpx;
		height: 63rpx;
		background: #F8EDD6;
		border-radius: 8px;
		margin: 0 auto;
		color: #C87910;
		line-height: 63rpx;
		text-align: center;
		margin: 30rpx;
	}

	.user_image {
		width: 88rpx;
		height: 88rpx;
		border-radius: 50%;
		opacity: 1;
	}

	// 左侧聊天
	.chat_left {
		background: #FFFFFF;
		opacity: 1;
		border-radius: 20rpx;
		padding: 20rpx;
		word-break: break-all;
		margin-top: 50rpx;
	}

	//右侧聊天
	.chat_right {

		background: #EAA019;
		opacity: 1;
		border-radius: 20rpx;
		padding: 20rpx;
		word-break: break-all;
		margin-top: 50rpx;
		color: white;
	}

	//发的图片大小
	.chat_image {
		height: 400rpx;
		width: 300rpx;
	}

	.message {
		width: 690rpx;
		height: 106rpx;
		background: #F8EDD6;
		border-radius: 8rpx;
		font-size: 20rpx;
		display: flex;
		color: #C87910;
		margin: 0 auto;

	}

	.chat_input {
		width: 700rpx;
		height: 90rpx;
		background: #FFFFFF;
		box-shadow: 0px 6rpx 17rpx rgba(223, 223, 223, 0.32);
		opacity: 1;
		border-radius: 45rpx;
		margin: 0 auto;
		margin-top: 20rpx;
	}

	//底部功能图标
	.message_icon {
		height: 44rpx;
		width: 44rpx;
	}

	.chat_icon {
		width: 60rpx;
		height: 60rpx;
	}

	.chat_audio {
		height: 50rpx;
		width: 50rpx;
	}

	//表情包

	.bottom-emoji {
		background-color: white;
		position: relative;

		.emojis {
			height: 350rpx;
			display: flex;
			flex-direction: row;
			flex-wrap: wrap;
			overflow-y: scroll;
			box-sizing: border-box;

			.emoji {
				height: 12.5vw;
				width: 12.5vw;
				padding: 8px;
				box-sizing: border-box;
			}

			.bigemoji {
				height: 20vw;
				width: 20vw;
				padding: 10px;
				box-sizing: border-box;
			}
		}
	}

	//表情包
	.emoji-tab {
		box-sizing: border-box;
		border-bottom: 1px solid gray;

		.tabs {
			display: flex;
			height: 29px;
			flex-direction: row;
			padding-left: 10px;
			box-sizing: border-box;

			.single {
				display: flex;
				margin-top: 2px;
				width: 26px;
				height: 26px;
				padding: 2px;
				border-radius: 6px;
				box-sizing: border-box;
				margin-right: 8px;
			}

			.choosed {
				background-color: rgba(255, 255, 255, 0.7);
			}
		}
	}

	page {
		padding-bottom: 200rpx;
	}

	.voice_an {
		width: 300rpx;
		height: 300rpx;
		position: fixed;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -55%);
		background-color: rgba(41, 41, 41, 0.7);
		color: white;
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
		border-radius: 10rpx;

		.text {
			padding-top: 30rpx;
		}

		@keyframes runVoice {
			0% {
				height: 10%;
			}

			20% {
				height: 50%;
			}

			50% {
				height: 100%;
			}

			80% {
				height: 50%;
			}

			100% {
				height: 0%;
			}
		}

		.wave {
			width: 6rpx;
			height: 100%;
			margin-left: 10rpx;
			border-radius: 50rpx;
			background-color: #999;
			vertical-align: middle;
			display: inline-block;
		}

		.voice_an_icon {
			width: 200rpx;
			height: 100rpx;
			line-height: 50rpx;
			margin: 50rpx 0;
		}

		.voice_an_icon #one {
			animation: runVoice 0.6s infinite 0.1s;
		}

		.voice_an_icon #two {
			animation: runVoice 0.6s infinite 0.3s;
		}

		.voice_an_icon #three {
			animation: runVoice 0.6s infinite 0.6s;
		}

		.voice_an_icon #four {
			animation: runVoice 0.6s infinite 0.1s;
		}

		.voice_an_icon #five {
			animation: runVoice 0.6s infinite 0.3s;
		}

		.voice_an_icon #six {
			animation: runVoice 0.6s infinite 0.6s;
		}

		.voice_an_icon #seven {
			animation: runVoice 0.6s infinite 0.1s;
		}
	}
</style>
